import { DoubleLeftOutlined } from '@ant-design/icons';
import { Checkbox, Collapse, Space } from 'antd';
import React, { useState } from 'react';
import { DragTable } from '../CommonTable/components/DragTable';
import Typography from '../Typography';
import Style from './index.module.less';
import IconFont from '@/components/IconFont';

const { Panel } = Collapse;
function newMapFrom(map) {
    // const newData = new Map();
    // map.forEach((v, k) => {
    //   newData.set(k, v);
    // });
    return new Map([...map.entries()]);
}
function copyMap(originalMap) {
    return new Map([...originalMap.entries()]);
}
function getAllField(children) {
    const result = [];
    function dfs(children) {
        children.forEach((el) => {
            result.push(el.field);
            el.childrenNode && dfs(el.childrenNode);
        });
    }
    dfs(children);
    return result;
}
const AllCheckBox = (props) => {
    const { childrenNode = [], checkedColumns, onCheckedColumnsChange, ...args } = props;
    const allField = getAllField(childrenNode);
    // status
    const checkedField = allField.filter((el) => checkedColumns.get(el));
    const checkAll = checkedField.length === allField.length;
    const indeterminate = checkedField.length > 0 && checkedField.length < allField.length;
    function onCheckAllChange() {
        allField.forEach((el) => {
            checkedColumns.set(el, !checkAll);
        });
        onCheckedColumnsChange?.(newMapFrom(checkedColumns));
    }
    return <Checkbox indeterminate={indeterminate} checked={checkAll} onChange={onCheckAllChange} {...args} />;
};
const InvertCheckBox = (props) => {
    const { childrenNode = [], checkedColumns, onCheckedColumnsChange, ...args } = props;
    const allField = getAllField(childrenNode);
    function onInvertChange() {
        allField.forEach((el) => {
            if (checkedColumns) {
                checkedColumns.set(el, !checkedColumns.get(el));
            }
        });
        onCheckedColumnsChange?.(newMapFrom(checkedColumns));
    }
    return <Checkbox checked={true} onChange={onInvertChange} {...args} />;
};
/**
 * 编辑指标弹窗
 * 传入树结构的数据，可以编辑指标的显示隐藏
 */
export const EditIndexModal = React.memo((props) => {
    const { onAscChange, onDescChange, checkedColumns, onCheckedColumnsChange, value, showAllCheckBox, ...args } = props;
    const [expand, setExpand] = useState(new Set());

    const SimpleCheckBox = ({ key, id, field, allowSort }) => {
        return (<>
            <div className={Style['control-wrapper']}>
                <Checkbox key={field} checked={checkedColumns.get(field)} onChange={(e) => {
                    checkedColumns.set(field, e.target.checked);
                    onCheckedColumnsChange?.(newMapFrom(checkedColumns));
                }} />

                {allowSort && <div className={Style['control-icon-group']}>
                    <div className={Style['control-icon']} onClick={() => onAscChange?.(id, field)}>
                        <IconFont type={'iconarrow-up-copy'}></IconFont>
                    </div>
                    <div className={Style['control-icon']} onClick={() => onDescChange?.(id, field)}>
                        <IconFont type={'iconarrow-down-copy'}></IconFont>
                    </div>
                </div>}
            </div>
        </>
        );
    };
    const commonCheckBoxProps = {
        onCheckedColumnsChange,
        checkedColumns,
    };
    return (<DragTable rowKey="field" pagination={false} scroll={{
        y: 'max-content',
    }} value={value} columns={[
        !showAllCheckBox && {
            title: '序号',
            dataIndex: 'idx',
            width: 80,
            render(v, record, idx) {
                return idx + 1;
            },
        },
        {
            title: '字段',
            dataIndex: 'field',
            width: 199,
            render(v, record) {
                function renderWrap(record, children) {
                    return (<Collapse className={Style.collapse} ghost key={record.field} expandIcon={({ isActive }) => <DoubleLeftOutlined rotate={isActive ? 270 : 90} style={{ fontSize: '12px', color: '#4E5969' }} />} expandIconPosition="end" style={{ cursor: 'pointer' }} onChange={(active) => {
                        setExpand((pre) => {
                            const isChecked = !!active.length;
                            const next = new Set(pre);
                            if (isChecked) {
                                next.add(record.field);
                            }
                            else {
                                next.delete(record.field);
                            }
                            return next;
                        });
                    }}>
                        {children}
                    </Collapse>);
                }
                function render(children, deep = 0) {
                    return children.map((child) => {
                        if (child.childrenNode) {
                            const node = (<Panel header={child.title} key={child.field}>
                                <Space direction="vertical" size={3}>
                                    {render(child.childrenNode, deep + 1)}
                                </Space>
                            </Panel>);
                            return deep ? renderWrap(child, node) : node;
                        }
                        return <p key={child.field}>{child.title}</p>;
                    });
                }
                return renderWrap(record, render([record]));
            },
        },
        {
            title: (<Space>
                <Typography as="s2" useBold>
                    是否显示
                </Typography>
                {showAllCheckBox && (<>
                    <AllCheckBox title="" field="" children="全选" childrenNode={value} {...commonCheckBoxProps} />
                    <InvertCheckBox title="" field="" children="反选" childrenNode={value} {...commonCheckBoxProps} />
                </>)}
            </Space>),
            width: 220,
            render(v, record) {
                function render(record) {
                    const childrenNode = record.childrenNode || [];
                    if (childrenNode.length) {
                        if (expand.has(record.field)) {
                            return (<React.Fragment key={record.field}>
                                <AllCheckBox key={record.field} {...record} {...commonCheckBoxProps} />
                                {childrenNode.map((el) => {
                                    if (el.childrenNode) {
                                        return render(el);
                                    }
                                    else {
                                        return <SimpleCheckBox key={el.field} id={record.field} allowSort={record?.allowSort} {...el} />;
                                    }
                                })}
                            </React.Fragment>);
                        }
                        return <AllCheckBox key={record.field} {...record} {...commonCheckBoxProps} />;
                    }
                    return <SimpleCheckBox {...record} />;
                }
                return (<Space className={Style.checkbox} direction="vertical" size={9}>
                    {render(record)}
                </Space>);
            },
        },
    ].filter(Boolean)} {...args} />);
});
export default EditIndexModal;
